"use client";

import React, { useState } from 'react';
import ComponentCard from '@/components/common/ComponentCard';
import Button from '@/components/ui/button/Button';
import InputField from '@/components/form/input/InputField';
import Badge from '@/components/ui/badge/Badge';

interface EntityInfo {
  id: string;
  name: string;
  type: string;
  addresses: string[];
  chains: string[];
  riskScore: number;
  confidence: number;
}

const AddressIntelligence: React.FC = () => {
  const [searchAddress, setSearchAddress] = useState('');
  const [entityInfo, setEntityInfo] = useState<EntityInfo | null>(null);
  const [loading, setLoading] = useState(false);

  // 搜索地址实体信息
  const searchEntity = async () => {
    if (!searchAddress.trim()) return;

    setLoading(true);
    try {
      // 获取地址画像（包含实体信息）
      const response = await fetch(
        `/api/analysis/address/${searchAddress}?chain=ethereum`
      );
      const data = await response.json();

      if (data.success && data.data.entity) {
        setEntityInfo(data.data.entity);
      }
    } catch (error) {
      console.error('搜索实体失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const getEntityTypeColor = (type: string) => {
    const colors: Record<string, { color: "primary" | "success" | "error" | "warning" | "info" | "light" | "dark"; variant: "light" | "solid" }> = {
      individual: { color: 'primary', variant: 'light' },
      institution: { color: 'info', variant: 'light' },
      exchange: { color: 'success', variant: 'light' },
      defi_protocol: { color: 'warning', variant: 'light' },
      unknown: { color: 'light', variant: 'light' }
    };
    return colors[type] || colors.unknown;
  };

  return (
    <div className="p-6 space-y-6">
      {/* Page Title */}
      <div>
        <h1 className="text-3xl font-bold text-gray-900 dark:text-white">Address Intelligence Analysis</h1>
        <p className="text-gray-600 dark:text-gray-400 mt-2">Deep dive into entity information and relationships behind addresses</p>
      </div>

      {/* Search Area */}
      <ComponentCard title="Entity Search">
        <div className="flex space-x-4">
          <div className="flex-1">
            <InputField
              placeholder="Enter address for entity analysis"
              onChange={(e: React.ChangeEvent<HTMLInputElement>) => setSearchAddress(e.target.value)}
            />
          </div>
          <Button 
            onClick={searchEntity}
            disabled={loading || !searchAddress.trim()}
          >
            {loading ? 'Analyzing...' : 'Search Entity'}
          </Button>
        </div>
      </ComponentCard>

      {/* Entity Information Display */}
      {entityInfo && (
        <div className="space-y-6">
          {/* Basic Entity Information */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <ComponentCard title="Basic Entity Information">
              <div className="space-y-4">
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Entity Name</p>
                  <p className="font-semibold text-gray-900 dark:text-white">{entityInfo.name}</p>
                </div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Entity Type</p>
                  <Badge {...getEntityTypeColor(entityInfo.type)}>
                    {entityInfo.type}
                  </Badge>
                </div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Risk Score</p>
                  <div className="flex items-center space-x-2">
                    <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
                      <div 
                        className={`h-2 rounded-full ${
                          entityInfo.riskScore > 70 ? 'bg-red-500' :
                          entityInfo.riskScore > 40 ? 'bg-yellow-500' : 'bg-green-500'
                        }`}
                        style={{ width: `${entityInfo.riskScore}%` }}
                      />
                    </div>
                    <span className="text-sm font-medium text-gray-900 dark:text-white">
                      {entityInfo.riskScore}/100
                    </span>
                  </div>
                </div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Confidence</p>
                  <p className="font-semibold text-gray-900 dark:text-white">
                    {(entityInfo.confidence * 100).toFixed(1)}%
                  </p>
                </div>
              </div>
            </ComponentCard>

            {/* Associated Addresses */}
            <ComponentCard title="Associated Addresses">
              <div className="space-y-2">
                {entityInfo.addresses.map((address, index) => (
                  <div key={index} className="flex items-center justify-between p-2 bg-gray-50 dark:bg-gray-800 rounded">
                    <span className="font-mono text-sm text-gray-900 dark:text-white">{address}</span>
                    <Badge color="light" variant="light">
                      {entityInfo.chains[index] || 'unknown'}
                    </Badge>
                  </div>
                ))}
              </div>
            </ComponentCard>
          </div>

          {/* Detailed Entity Analysis */}
          <ComponentCard title="Detailed Analysis">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              <div className="text-center">
                <p className="text-2xl font-bold text-blue-600">{entityInfo.addresses.length}</p>
                <p className="text-sm text-gray-600 dark:text-gray-400">Associated Addresses</p>
              </div>
              <div className="text-center">
                <p className="text-2xl font-bold text-green-600">{entityInfo.chains.length}</p>
                <p className="text-sm text-gray-600 dark:text-gray-400">Involved Chains</p>
              </div>
              <div className="text-center">
                <p className="text-2xl font-bold text-purple-600">
                  {entityInfo.type === 'institution' ? 'Institution' : 
                   entityInfo.type === 'exchange' ? 'Exchange' : 'Individual'}
                </p>
                <p className="text-sm text-gray-600 dark:text-gray-400">Entity Category</p>
              </div>
            </div>
          </ComponentCard>

          {/* Relationship Graph Placeholder */}
          <ComponentCard title="Entity Relationship Graph">
            <div className="h-96 bg-gray-50 dark:bg-gray-800 rounded-lg flex items-center justify-center">
              <div className="text-center text-gray-500 dark:text-gray-400">
                <p>Relationship graph feature under development...</p>
                <p className="text-sm mt-1">Will display complex association networks between entities</p>
              </div>
            </div>
          </ComponentCard>
        </div>
      )}

      {/* No Results State */}
      {!entityInfo && searchAddress && !loading && (
        <ComponentCard title="Search Results">
          <div className="text-center text-gray-500 dark:text-gray-400 py-8">
            <p>No related entity information found</p>
            <p className="text-sm mt-1">Please try other addresses or try again later</p>
          </div>
        </ComponentCard>
      )}
    </div>
  );
};

export default AddressIntelligence; 